let domTRarr = [];
let nodeActive = null;
let currentSeleRow = 0;
let resData = null;

$NG.AllReady(function (
	page,
	{ useDataIndexChange, useUpdateRow, useUpdateRows, useValuesChange, useClick }
) {
	// 编辑页面逻辑
	const mstform = $NG.getCmpApi("p_form_integrated_apply_m");
	const grid1 = $NG.getCmpApi("p_form_integrated_apply_d1");
	const grid2 = $NG.getCmpApi("p_form_integrated_apply_d2");
	const getItemValue = (itemName) => mstform.getItem(itemName).getValue();
	/**
	 *@default: 初始化
	 */

	//  $NG
	//  .getCmpApi("p_form_integrated_apply_m")
	//  .getItem("u_bus_no")
	//  .getRef()
	//  .click(()=>{
	//     console.log(`被点击了`);
	//  });

	$NG.updateUI((updater, state) => {
		console.log(`过滤`, updater);
		updater.form.p_form_integrated_apply_m.u_bus_no.setProps({
			onDoubleClick() {
				console.log(`被点击了`);
				onT();
			},
		});
	});

	if (page.oType == "add") {
		if ($NG.getCmpApi("p_form_integrated_apply_m")) {
			getPtInfoByPhid();
		}
	}

	/**
	 *@license: 	 //表头字段变化逻辑END	//表头字段变化逻辑BEGIN
	 */
	useValuesChange(({ args }) => {
		getPtInfoByPhid();
	}, "p_form_integrated_apply_m.phid_pc");
    useValuesChange(({args})=>{
        setTimeout(()=>{
            ajaxGet()
        },200)
    },"p_form_integrated_apply_m.u_pc_pre_sales")
	/**
	 *@license: 	 //u_sqlx	//u_sqlx
	 */
	useValuesChange(({ args }) => {
		console.log("args", args);
	}, "p_form_integrated_apply_m.u_sqlx");
	/**
	 *@license: 	 //表头字段变化逻辑END	//表头字段变化逻辑BEGIN
	 */
	useValuesChange(({ args, instance }) => {
		console.log("args111", args);
		calcCostRedRate();
	}, "p_form_integrated_apply_m.u_pur_amt");

	/**
	 *@license:设备物资表 计算
	 */

	useUpdateRows(({ args }) => {
		console.log(args[0], "args");
		let sumAmt1 = 0;
		let sumAmt2 = 0;
		let sumAmt3 = 0;
		let sumAmt4 = 0;
		let rows = args[0];
		rows.forEach((row) => {
			sumAmt1 += calcTargetAmt(row.u_target_prc, row.u_qty); //  目标价格 *数量 = 目标价格金额;
			sumAmt2 += calcMarketAmt(row.u_prc, row.u_qty); //  市场价格 *数量 = 市场平均金额;
			sumAmt3 += calcPreSaleAmt(row.u_pre_sale_amt, row.u_qty); //  市场价格 *数量 = 售前议价金额;
			sumAmt4 = calcCostRedRate();
			if (!row.u_is_scbzwl) {
				row.u_is_scbzwl = "1";
				row.u_is_scbzwl_EXName = "是";
			}
			console.log(row, "物料单个");
			if (row.u_unit && row.u_item_name && row.u_spec) {
				console.log(row.u_unit, row.u_item_name, row.u_spec);
				$NG.execServer(
					"getItemdataPhid",
					{
						phid_unit: row.u_unit,
						itemname: `'${row.u_item_name}'`,
						spec: `'${row.u_spec}'`,
					},
					function (res) {
						const datas = JSON.parse(res.data)[0].extendObjects;
						console.log(datas.phid, "查询物料phid");
						console.log(datas, "查询物料phid");
						row.u_item_no = datas.phid;
						row.u_item_no_EXName = datas.itemno;
						row.u_item_sub = datas.phid_resbs; //单位
						row.u_item_sub_EXName = datas.name; //单位

						grid1.refreshView();
					}
				);
			}

			if (row.u_item_no) {
				$NG.execServer(
					"getItemdataByPhid",
					{ phid: row.u_item_no },
					function (res) {
						const datas = JSON.parse(res.data)[0].extendObjects;
						console.log(datas, "xxxxxxxx");
						row.u_item_name = datas.itemname;
						row.u_spec = datas.spec;
						row.u_unit = datas.msunit_phid;
						row.u_unit_EXName = datas.msunit_name; //单位
						row.u_item_sub = datas.res_bs_phid; //单位
						row.u_item_sub_EXName = datas.res_bs_name; //单位
						grid1.refreshView();
					}
				);
			}

			//汇总赋值
			$NG.updateState((updater) => {
				updater.data.p_form_integrated_apply_m.setProps({
					u_tar_amt: sumAmt1,
					u_ave_amt: sumAmt2,
					u_sqyj_amt: sumAmt3,
					u_cost_red_rate: sumAmt4,
				});
			});
		});
		grid1.refreshView();
		// row.u_qty; //数量
		// row.u_target_prc; //目标价格
		// row.u_pre_sale_amt; //售前议价结果
		// row.u_pur_prc; //最终采购价
		// row.u_prc; //市场价
	}, "p_form_integrated_apply_d1");

	/**
	 *@function:带出项目信息
	 */
	function getPtInfoByPhid() {
		if (mstform.getItem("phid_pc").getValue()) {
			$NG.execServer(
				"getPtInfoByPhid",
				{ phid: mstform.getItem("phid_pc").getValue() },
				function (res) {
					const datas = JSON.parse(res.data)[0].extendObjects;
					console.log(datas, "datas");
					//帮助字段赋值
					$NG.updateState((updater) => {
						updater.data.p_form_integrated_apply_m.setProps({
							// u_supply_att: datas.u_supply_att, //计划完工日期
							// u_supply_name: datas.u_supply_name, //计划竣工日期
							u_pc_no: datas.pc_no, //项目编码
							phid_org: {
								//事业部or组织
								value: datas.org_phid,
								label: datas.org_name,
							},
							u_regional_center: {
								//区域中心
								value: datas.regional_center_phid,
								label: datas.regional_center_name,
							},
							u_product_line: {
								//产品线
								value: datas.midwife_phid,
								label: datas.midwife_name,
							},
							u_pc_pre_sales: {
								value: datas.user_sqgw_phid,
								label: datas.user_sqgw_name, //销售顾问
							},
							u_department: {
								value: datas.dept_phid,
								label: datas.dept_name, //部门
							},
							bill_name: mstform.getValues().phid_pc_EXName + "定价申请",
						});
                        setTimeout(()=>{
                            ajaxGet()
                        },200)

					});
					$NG.execServer(
						"projectSjbm",
						{ phid: mstform.getItem("phid_pc").getValue() },
						function (res) {
							const datas = JSON.parse(res.data)[0].extendObjects;

							if (datas.user_sjbm) {
								$NG.execServer(
									"isYzPush",
									{ sjno: `'${datas.user_sjbm}'` },
									function (res1) {
										try {
											if (res1.data > 0) {
												const datas1 = JSON.parse(res1.data)[0].extendObjects;
												console.log(datas1, "datas1"); //判断是否已推送
												$NG.updateState((updater) => {
													updater.data.p_form_integrated_apply_m.setProps({
														u_is_yztj: { value: 1, label: "是" },
													});
												});
											} else {
												console.log(res1.data, "res1.data");
												$NG.updateState((updater) => {
													updater.data.p_form_integrated_apply_m.setProps({
														u_is_yztj: { value: 2, label: "否" },
													});
												});
											}
										} catch (error) {
											console.log(error, "isYzPush??");
										}
									}
								);
							} else {
								$NG.updateState((updater) => {
									updater.data.p_form_integrated_apply_m.setProps({
										u_is_yztj: { value: 2, label: "否" },
									});
								});
							}

							$NG.updateState((updater) => {
								updater.data.p_form_integrated_apply_m.setProps({
									u_bus_no: datas.user_sjbm, //项目编码
									u_sj_name: datas.user_sjmc, //项目名称
								});
							});
						}
					);
				}
			);
		}
	}

	/**
	 *@function:目标价格金额 计算
	 */
	function calcTargetAmt(targePrice, num) {
		return targePrice * num;
	}

	/**
	 *@function:市场平均金额 计算
	 */

	function calcMarketAmt(targePrice, num) {
		return targePrice * num;
	}
	/**
	 *@function:售前议价金额 计算
	 */
	function calcPreSaleAmt(targePrice, num) {
		return targePrice * num;
	}

	/**
	 *@function:降成本率 计算
	 */
	function calcCostRedRate() {
		// 获取值并校验
		const sqyjAmt = parseFloat(getItemValue("u_sqyj_amt")) || 0; // 售前议价金额
		const purAmt = parseFloat(getItemValue("u_pur_amt")) || 0; // 最终采购价格

		// 检查售前议价金额是否为 0
		if (sqyjAmt === 0) {
			console.error("售前议价金额为 0 或无效，无法计算。");
		} else {
			// 计算差额百分比
			const percentageDiff = (sqyjAmt - purAmt) / sqyjAmt;
			console.log("差额百分比：", percentageDiff);

			// 如果需要输出百分比格式
			const percentageFormatted = (percentageDiff * 100).toFixed(2);
			console.log("格式化结果：", percentageFormatted + "%");

			$NG.updateState((updater) => {
				updater.data.p_form_integrated_apply_m.setProps({
					u_cost_red_rate: percentageFormatted,
				});
			});
		}
	}

	/**
	 *@function:损失率 计算
	 */

	function calcLossRate() {
		// 获取值并校验
		const sqyjAmt = parseFloat(getItemValue("u_sqyj_amt")) || 0; // 售前议价金额
		const purAmt = parseFloat(getItemValue("u_ave_amt")) || 0; // 市场平均金额
		return sqyjAmt - purAmt;
	}
	// // /10.表体数据变化（增行、删行、引入）时，汇总计算至表头
	// useUpdateRows(({ args }) => {
	// 	var sumAmt = 0;
	// 	const rows = args[0];
	// 	rows.forEach((items) => {
	// 		if (items.u_target_prc && items.u_qty) {
	// 			sumAmt += parseFloat(items.u_target_prc * items.u_qty);
	// 		}
	// 		//汇总赋值
	// 		$NG.updateState((updater) => {
	// 			updater.data.p_form_integrated_apply_m.setProps({
	// 				u_tar_amt: sumAmt,
	// 			});
	// 		});
	// 	});
	// }, "p_form_integrated_apply_d1");
});

//表体u_qty*u_pur_prc=表头u_pur_amt

//表体u_qty*u_prc=表头u_ave_amt

const style = document.createElement("style"); // 创建一个新的 <style> 元素
const cssRules = `
 
        .zdy-bigBox{
            background:white;
            width: 60vw;
            height:60vh;
            top:15vh;
            left:20vw;
            border-radius:4px;
        }
        .zdy-tableHeader{
            border-bottom:1px #d3d3d3 solid;
            padding:1vh 0 ;
            display:flex;
            justify-content: space-between;
        }
        .zdy-header-button{
            width:35%;
        }
        .zdy-header-button input{
            border:1px #d3d3d3 solid;
            border-radius: 4px;
            height:100%;
            width:80%;
            font-size:40%;
            outline: none;
            padding-left:2px;
        }
        .zdy-header-button button{
            width:2vw;
            height:2vw;
        }
        .zdy-title{
            border-left:4px #1677ff solid;
            padding:0 0 0 0.5vw ;
        }
        .header{
            display:flex;
        }
        /* tabs */
        .zdy-tabs-box{
            width:100%;
            height:8%;
            border:1px green solid;
        }
        .zdy-tabs-box ul{
            width:auto;
            height:100%;
            padding-left:2%;
            display:flex;
            list-style: none;
            font-size:90%;
            align-items:end;
        }
        .zdy-tabs-box li{
            height:auto;
            margin-right:10%;
            border-bottom:#1677ff solid 2px;
        }
        .zdy-table{
            width:100%;
            border-collapse: collapse;
            overflow:hidden;
            text-align:left;
            background:#fff;
        }
        .zdy-table-box{
            margin:1% auto;
            width:98%;
            height:80%;
            overflow-y:scroll;
        }
        .zdy-table tr{
            height: 30px;
            border-bottom:1px #d0d0d0 solid;
            /*border:1px black solid;*/
            transition: all 0.2s linear;
        }
        .zdy-table td,.zdy-table th{
            padding:1.5% 0;
            /*border:1px black solid;*/
        }
        .zdy-table-thead-tr,zdy-table-tbody-tr{
            vertical-align: top;
        }
        .zdy-table-thead-tr th{
            height:10px;
        }
        .zdy-col-box{
            width:100%;
            display:none;
            height:5%;
            ul{
                list-style: none;
                display:flex;
            }
        }
        .zdy-box-page{
            width:100%;
            display:flex;
        }
        .zdy-btn-ok{
            width:100%;
            height:5%;
            display:flex;
            justify-content: end;
        }
        .zdy-btn-ok button{
            margin-right:5%;
            width:6vw;
        }
        .zdy-btn-box{
            display:flex;
        }
            .zdy-active{
            background-color: hsl(215, 100%, 94%);
        }
            #zdy-main{
                background:#0000007a;
                width:100%;
                height:100vh;
                position:fixed;
                top:0;
                left:0;
                z-index:999;
                display:none;
                justify-content: center;
                align-items:center
            }
`;
style.textContent = cssRules; // 设置 <style> 元素的内容为CSS规则字符串
document.head.appendChild(style);

TestBody();
ajaxGet();
//关闭
function offT() {
	document.querySelector("#zdy-main").style.display = `none`;
}
//开启
function onT() {
	document.querySelector("#zdy-main").style.display = `flex`;
}
function TestBody() {
	let code = `
        <div id="zdy-main">
            <div class="zdy-bigBox" >
        <!-- 表头 start -->
        <div class="zdy-tableHeader">
            <h5 class="zdy-title">商机信息</h5>
            <div class="zdy-header-button">
                <input type="text" placeholder="请输入关键词">
                <button id="X">X</button>
            </div>
        </div>
        <!-- 表头 end -->

        <!-- Tabs start -->
         <div class="zdy-col-box">
            <ul>
                <li>所有数据</li>
            </ul>
         </div>
         <!-- Tabs end -->

         <!-- 表体 start -->
          <div class="zdy-table-box">
              <table class="zdy-table" id="zdy-table">
                
                  
              </table>
          </div>
         <!-- 表体 end -->
<!--        分页控件 start-->
        <div class="zdy-col-box">
            <p>第1-20条/总共 70条</p>
            <div class="zdy-box-page">
                <button><</button>
                <ul>
                    <li>1</li>
                    <li>2</li>
                    <li>3</li>
                    <li>4</li>
                </ul>
                <button>></button>
            </div>
        </div>
        <!--        分页控件 end-->
        <div class="zdy-btn-ok">
           <div class="zdy-btn-box">
               <button id="zdy-btn-off">取消</button>
               <button id="zdy-btn-on">确定</button>
           </div>
        </div>
    </div>
        </div>
    `;
	document.querySelector("#root").insertAdjacentHTML("beforeend", code);
	document.querySelector("#zdy-btn-off").addEventListener("click", (e) => {
		offT();
        if(!nodeActive)return
		nodeActive.classList.remove("zdy-active");
		currentSeleRow = -1;
	});
    document.querySelector("#X").addEventListener("click", (e) => {
		offT();
        if(!nodeActive)return
		nodeActive.classList.remove("zdy-active");
		currentSeleRow = -1;
	});
	//TODO 缺少字段
	document.querySelector("#zdy-btn-on").addEventListener("click", (e) => {
		console.log(resData[currentSeleRow]);
		const _data = resData[currentSeleRow];
		if (currentSeleRow !== -1) {
			$NG.updateState((updater) => {
				updater.data.p_form_integrated_apply_m.setProps({
					u_bus_no: _data.ProjectNo__c,
					u_sj_name: _data.name,
					u_tar_amt: _data.field_3blb1__c,
				});
			});
		}
		nodeActive.classList.remove("zdy-active");
		currentSeleRow = -1;
		offT();
	});
}
// 请求服务器
function ajaxGet() {
    const mstform = $NG.getCmpApi("p_form_integrated_apply_m")
    console.log('调用ajaxGet');
    if(!mstform.getItem('u_bus_no').getValue()){
        let str = `
            <h4>获取帮助失败，请重新选择售前或者选择项目</h4>
    `;
    document.querySelector("#zdy-table").innerHTML=str
    return
    }
    $NG.execServer("getBusNo",{phid:mstform.getItem("u_pc_pre_sales").getValue()},(res)=>{
        console.log(`查找编码`,res);
        if(res.count == 0 ){
            let str = `
            <h4>当前项目售前字段数据存在问题，可能是没编码！</h4>
    `;
    document.querySelector("#zdy-table").innerHTML=str
        }
        const _data = JSON.parse(res.data)[0].extendObjects
        //发请求
        const xhr = new XMLHttpRequest();
	xhr.open(
		"POST",
		"http://nginx.clouddev.hisense.com/sd/sdToCrm/apply/opportunity/query"
	);
	xhr.setRequestHeader("Content-Type", "application/json");
	xhr.send(
		JSON.stringify({
			name:String(_data.bill_no),
		})
	);
	let str = `
     <thead>
        <tr class="zdy-table-thead-tr">
            <th>商机编码</th>
            <th>商机名称</th>
            <th>项目金额</th>
            <th>预计签单时间</th>
        </tr>
    </thead>
    <tbody>
    `;
	xhr.onreadystatechange = function () {
		if (xhr.readyState === 4 && xhr.status === 200) {
			var response = JSON.parse(xhr.responseText);
			console.log("服务器端返回的响应:", response);
            if(response.length==0){
                str = `
            <h4>当前项目售前无数据</h4>
    `;
    document.querySelector("#zdy-table").innerHTML=str
    return
            }
			resData = response;
			resData.forEach((item) => {
				str += `
                     <tr class="zdy-table-tbody-tr">
                        <td>${item.ProjectNo__c}</td>
                        <td>${item.name}</td>
                        <td>${item.field_3blb1__c}</td>
                        <td>${item.expected_signing_time_text__c}</td>
                    </tr>
                `;
			});
			str += "</tbody></table>";
			// document.querySelector("#zdy-table").addEventListener
			document.querySelector("#zdy-table").insertAdjacentHTML("beforeend", str);
			if (domTRarr) {
				domTRarr.forEach((item) => {
					item.removeEventListener("click", itemFC());
				});
			}
			domTRarr = document.querySelectorAll(".zdy-table-tbody-tr");
			domTRarr.forEach((item, index) => {
				item.addEventListener("click", (e) => {
					itemFC(e, index);
				});
				item.addEventListener("dblclick", () => {
					console.log(`双击事件`);
					dbClick();
				});
			});
		} else {
			console.log(`状态`,xhr.readyState);
		}
	};
    })
	
	//双击触发事件
	function dbClick() {
		const _data = resData[currentSeleRow];
		currentSeleRow = -1;
		document.querySelector("#zdy-main").style.display = `none`;
		try {
			nodeActive.classList.remove("zdy-active");
		} catch (e) {}
		$NG.updateState((updater) => {
			updater.data.p_form_integrated_apply_m.setProps({
				u_bus_no: _data.ProjectNo__c,
				u_sj_name: _data.name,
			});
		});
	}
	// 点击逻辑
	function itemFC(e, index) {
		currentSeleRow = index;
		console.log(e, "qf");
		if (e.target instanceof HTMLTableCellElement) {
			const pre = e.target.parentNode;
			if (pre instanceof HTMLTableRowElement) {
				if (nodeActive) {
					nodeActive.classList.remove("zdy-active");
				}
				nodeActive = pre;
				nodeActive.classList.add("zdy-active");
			}
		}
	}
}
